package com.yixincaipiao.network;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.yixincaipiao.exception.BaseException;
import com.yixincaipiao.exception.HttpDataErrorException;
import com.yixincaipiao.ui.account.Account;

/**
 * 描述：万能分页类！ <br>
 */
public abstract class Page<T> {
    Class<T> entityClass;

    public int mPageSize = 10;// 每页显示个数

    private int mCurrentPage = 1;// 当前页
    private int mTotalPage = 0;// 总页数
    private int mTotalCount = 0;// 总数量

    private Context mContext;

    private String mUrl = null;

    public Page(Context mContext, String url, Class<T> clazz) {
        this.mContext = mContext;
        mUrl = url;
        entityClass = clazz;
        // entityClass =
        // (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    private boolean isWithAccount = false;
    private String[] keys = null;
    private Object[] values = null;

    public void setIsWithAccount(boolean isWithAccount) {
        this.isWithAccount = isWithAccount;
    }

    public void setParams(String[] keys, Object[] values) {
        this.keys = keys;
        this.values = values;
    }

    /**
     * 访问第一页
     *
     * @param isWithAccount 是否需要用户校验
     */
    public void init(boolean isWithAccount) {
        this.isWithAccount = isWithAccount;
        init();
    }

    /**
     * 访问第一页
     *
     * @param isWithAccount 是否需要用户校验
     * @param keys          values 其他参数key values
     */
    public void init(boolean isWithAccount, String[] keys, Object[] values) {
        this.isWithAccount = isWithAccount;
        this.keys = keys;
        this.values = values;
        init();
    }

    /**
     * 访问第一页
     */
    public void init() {
        mCurrentPage = 1;
        mTotalCount = 0;
        mTotalPage = 0;
        request();
    }

    /**
     * 功能描述： 以map的形式传参<br>
     *
     * @param
     */
    public void init(boolean isWithAccount, Map<String, Object> param) {
        this.isWithAccount = isWithAccount;
        List<String> keyList = new ArrayList<String>();
        List<Object> valueList = new ArrayList<Object>();
        Iterator it = param.keySet().iterator();
        while (it.hasNext()) {
            String keyStr = it.next().toString();
            keyList.add(keyStr);
            valueList.add(param.get(keyStr));
        }
        String[] keyAry = new String[]{};
        this.keys = keyList.toArray(keyAry);
        this.values = valueList.toArray();
        init();
    }

    /**
     * 下一页
     *
     */
    public void nextPage() {
        if (mTotalPage <= 0 || (mTotalPage > 0 && this.mCurrentPage <= this.mTotalPage)) {
            this.mCurrentPage += 1;               // 在请求之前设置当前页面状态， 如果请求异常会导致串页
        }
        request();
    }

    public boolean isFirstPage() {
        return mCurrentPage == 1;
    }

    public boolean isLastPage() {
        return mCurrentPage >= mTotalPage;
    }

    public void setPageSize(int pageSize) {
        this.mPageSize = pageSize;
    }

    public int getTotalCount() {
        return mTotalCount;
    }

    public int getTotalPage() {
        return mTotalPage;
    }

    private boolean isRequestSuccess;

    public boolean getIsRequestSuccess() {
        return isRequestSuccess;
    }

    protected void request() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("onePageCount", mPageSize);
        params.put("nowPage", mCurrentPage);

        if (keys != null && values != null && keys.length != 0 && values.length != 0) {
            for (int i = 0; i < values.length; i++) {
                params.put(keys[i], values[i]);
            }
        }

        if (isWithAccount) {//after  添加用户数据    17\5\3
//            params.put("phone", Account.Instance(mContext).getmUserBean().getPhone());
//            params.put("password", Account.Instance(mContext).getmUserBean().getPass());
//            params.put("userName", Account.Instance(mContext).getmUserBean().getUserName());
        }
        Http.aSyncPost(mContext, null, mUrl, params, new NetRequest.NetRequestListener() {

            @Override
            public void onAccessComplete(boolean success, String object, VolleyError error, String flag) {

                isRequestSuccess = success;
                if (!success) {
                    onRequestError(VolleyErrorMsg.getMessage(error));
                    return;
                }
                if (object == null || "".equals(object)) {
                    onRequestError(VolleyErrorMsg.getMessage(error));
                    return;
                }
                String data = "";
                // 数据解析
                try {
                    data = Http._analysData(object);
                } catch (BaseException e1) {
                    onRequestError(e1.getMessage());
                    return;
                }

                try {
                    JSONObject json = new JSONObject(data);

                    if (mCurrentPage <= 1) {
                        if (!json.isNull("page")) {
                            mTotalPage = json.getInt("page");
                        }
                        if (!json.isNull("total")) {
                            mTotalCount = json.getInt("total");
                        }
                    }

                    Gson gson = new Gson();
                    ArrayList<T> arrayList = new ArrayList<T>();
                    if (!json.isNull("data")) {
                        JSONArray jsonArray = json.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            T t = gson.fromJson(jsonArray.getString(i), entityClass);
                            arrayList.add(t);
                        }
                    }
                    onRequestOk(arrayList);
                } catch (Exception e) {
                    e.printStackTrace();
                    onRequestError(new HttpDataErrorException().getMessage());
                }

            }
        });
    }

    public abstract void onRequestOk(List<T> list);

    public abstract void onRequestError(String msg);

}
